package com.guo.worktool.service.impl;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.file.WatchEvent;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.codec.binary.Base64;



/**
 * @program: WorkTool
 * @author: Mr.GUO
 * @create: 2023-03-13 12:39
 **/

public class SQLWorkToolServiceImpl {


    public static String assemblyDataByIdorName(String[] split, String type){
//        System.out.println(Arrays.toString(split));
        StringBuilder sb = new StringBuilder();
        StringBuilder failureSb = new StringBuilder();
        int count = 0;
        sb.append("and ").append(type).append(" in (");
        for (String str : split){
            if (StringUtils.isNotEmpty(str)){
                if (str.length() > 18){
                    failureSb.append("\n数据格式不正确:").append(str);
                    continue;
                }
                sb.append("\'").append(str).append("\',");
                count++;
            }
        }
        sb.deleteCharAt(sb.length()-1);
        sb.append(");\n\n");
        if (count < 1){
            sb.setLength(0);
        }
        sb.append("成功处理数据").append(count).append("条\n");
        sb.append(failureSb);
        return sb.toString();
    }

    public static String assemblyDataByIdNo(String[] split){
//        System.out.println(Arrays.toString(split));
        StringBuilder sB = new StringBuilder();
        StringBuilder sB1 = new StringBuilder();
        int count  = 0;
        int falseCount = 0;
        sB.append("and id_no in (");
        for (int i = 0; i < split.length; i++) {
            if (StringUtils.isEmpty(split[i])){
                continue;
            }
            if (split[i].trim().length() != 18){
                falseCount++;
                sB1.append("\n第" + (i+1) + "行：身份证号码不是18位：").append(split[i]);
                continue;
            }
            ShardingAesEncrypt shardingAesEncrypt = new ShardingAesEncrypt("eyHXTWVo&B69");
            String encrypt = shardingAesEncrypt.encrypt(split[i]);  //加密
            count++;
            sB.append("\'").append(encrypt).append("\'").append(",");
        }
        sB.deleteCharAt(sB.length()-1);
        sB.append(");\n\n");
        if (count < 1){
            sB.setLength(0);
        }
        sB.append("成功处理数据").append(count).append("条")
                .append(",失败数据").append(falseCount).append("条:").append(sB1);
//        System.out.println(sB);
        return sB.toString();
    }


    public static String assemblyDataOutForm(String[] split){
        StringBuilder sb = new StringBuilder();
        String last = split[split.length - 1];
        String blN = "";
        String blStr = "";
        if(!last.contains("-")){
//            return "最后一行为变量命名, 例如formParams-webResponse";
            blN = "paramMap";
            blStr = "webResponse";
        }else {
            String[] blName = last.split("-",2);
            blN = blName[0];
            blStr = blName[1];
        }

        String prefix = "Map<String,String> zdyData  = Maps.newLinkedHashMap();\n";
        sb.append(prefix);
        for (String str : split) {
            if(str.contains(":")){
                String[] two = str.split(":",2);
                sb.append("zdyData.put(\"").append(two[0]).append("\", ")
                        .append(JSON.toJSONString(two[1].trim())).append(");")
                        .append("\n");
            }
        }
        sb.append("log.info(\"zdyData {}\", zdyData);").append("\n");
        sb.append("String ").append("zdyStr")
                .append("= CommentRequestUtil.requestXXXBackJSONObject(gjjWebClientTL.get(), \"\", zdyData);")
                .append("\n");
        sb.append("log.info(\"zdyStr {}\", zdyStr);").append("\n");
        String returnStr = sb.toString();
        returnStr = returnStr.replace("zdyData",blN);
        returnStr = returnStr.replace("zdyStr",blStr);
        return returnStr;
    }



    public static String assemblyDataOutForm0(String[] split){
        StringBuilder sb = new StringBuilder();
        String last = split[split.length - 1];
        String blN = "";
        if(!last.contains("-")){
            blN = "formParams";
        }else {
            String[] blName = last.split("-",2);
            blN = blName[0];
        }
        int count = 0;
        String prefix = "List<NameValuePair> zdyData = new ArrayList<>();\n";
        sb.append(prefix);
        for (String str : split) {
            if(str.contains(":")){
                String[] two = str.split(":",2);
                sb.append("zdyData.add(new NameValuePair(\"").append(two[0]).append("\", ")
                        .append(JSON.toJSONString(two[1].trim())).append("));")
                        .append("\n");
                count++;
            }
        }
        sb.append("log.info(\"zdyData:{}\", zdyData);\n");
        sb.append("成功处理了").append(count).append("条");
        String returnStr = sb.toString();
        returnStr = returnStr.replace("zdyData",blN);
        return returnStr;
    }

    public static String assemblyDataOutFormJSON(String str){
        try {
            StringBuilder sb = new StringBuilder();
            JSONObject jsonObject = JSONObject.parseObject(str);
            String prefix = "List<NameValuePair> formParams = new ArrayList<>();\n";
            sb.append(prefix);

            jsonObject.forEach((k,v) ->
                    sb.append("formParams.add(new NameValuePair(\"").append(k).append("\", ")
                            .append("\"").append(v).append("\"").append("));")
                            .append("\n")
            );
            sb.append("log.info(\"入参 : {}\", JSON.toJSONString(formParams));\n");
            String returnStr = sb.toString();
            return returnStr;
        }catch (Exception e){
            return "造轮子是个技术活，你超出了轮子的范围！";
        }

    }

    public static String assemblyDataOutFormYs(String[] split){
        StringBuilder sb = new StringBuilder();
        if(split.length<1){
            return sb.toString();
        }
        String last = split[split.length - 1];
        if(!last.contains("-")){
            return "最后一行为变量命名,例如p1-s1";
        }
        String[] blName = last.split("-",2);
        String blN = blName[0];
        String blStr = blName[1];
        String prefix = "Map<String,String> zdyData  = Maps.newLinkedHashMap();\n";
        sb.append(prefix);
        for (String str : split) {
            if(str.contains(":")){
                String[] two = str.split(":",2);
                sb.append("zdyData.put(\"").append(two[0]).append("\",")
                        .append(JSON.toJSONString(two[1].trim())).append(");")
                        .append("\n");
            }
        }
        sb.append("log.info(\"zdyData {}\",zdyData);").append("\n");
        sb.append("String ").append("zdyStr")
                .append("= CommentRequestUtil.requestXXXBackJSONObject(gjjWebClientTL.get(), \"\", zdyData);")
                .append("\n");
        sb.append("log.info(\"zdyStr {}\",zdyStr);").append("\n");
        String returnStr = sb.toString();
        returnStr = returnStr.replace("zdyData",blN);
        returnStr = returnStr.replace("zdyStr",blStr);
        return returnStr;
    }

    public static void main(String[] args) {
        String[] split = {"张三","王五"};
//        assemblyDataByIdorName(split, "name");
        String str = "params: [{\"grzh\":\"1001168873\",\"xingming\":\"朱宴\"}]\n" +
                "yhdllb: 02\n" +
                "exeType: deleteDwgrkhsq\np1-s1";
        System.out.println(assemblyDataOutForm(str.split("\n")));

    }
















    static class ShardingAesEncrypt {
        private String aesKey;

        public ShardingAesEncrypt(String aesKey) {
            this.aesKey = aesKey;
        }

        private String getType() {
            return "AES";
        }

        public String encrypt(String plaintext) {
            try {
                if (isBlank(plaintext)) {
                    return plaintext;
                } else {
//                    byte[] result = this.getCipher(1).doFinal(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(plaintext));
                    byte[] result = this.getCipher(1).doFinal(plaintext.getBytes(Charset.forName("UTF-8")));
                    return encodeBase64String(result);
                }
            } catch (Throwable var3) {
                return plaintext;
            }
        }
        public static String encodeBase64String(byte[] binaryData) {
            return newStringUsAscii(encodeBase64(binaryData, false));
        }
        public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked) {
            return encodeBase64(binaryData, isChunked, false);
        }
        public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe) {
            return encodeBase64(binaryData, isChunked, urlSafe, Integer.MAX_VALUE);
        }
        public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked,
                                          final boolean urlSafe, final int maxResultSize) {
            if (binaryData == null || binaryData.length == 0) {
                return binaryData;
            }
            final byte[] CHUNK_SEPARATOR = {'\r', '\n'};
            // Create this so can use the super-class method
            // Also ensures that the same roundings are performed by the ctor and the code
            final Base64 b64 = isChunked ? new Base64(urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe);
            final long len = b64.getEncodedLength(binaryData);
            if (len > maxResultSize) {
                throw new IllegalArgumentException("Input array too big, the output array would be bigger (" +
                        len +
                        ") than the specified maximum size of " +
                        maxResultSize);
            }

            return b64.encode(binaryData);
        }
        private Cipher getCipher(int decryptMode) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
            Cipher result = Cipher.getInstance(this.getType());
            result.init(decryptMode, new SecretKeySpec(this.createSecretKey(), this.getType()));
            return result;
        }
        private byte[] createSecretKey() {
            return Arrays.copyOf(sha1(this.aesKey), 16);
        }
        public static byte[] sha1(String data) {
            return sha1(getBytesUtf8(data));
        }
        public static byte[] getBytesUtf8(String string) {
            return getBytes(string, Charset.forName("UTF-8"));
        }

        public static String newStringUsAscii(byte[] bytes) {
            return newString(bytes, Charset.forName("US-ASCII"));
        }
        private static String newString(byte[] bytes, Charset charset) {
            return bytes == null ? null : new String(bytes, charset);
        }



        public static byte[] sha1(byte[] data) {
            return getSha1Digest().digest(data);
        }
        public static MessageDigest getSha1Digest() {
            return getDigest("SHA-1");
        }
        public static MessageDigest getDigest(String algorithm) {
            try {
                return MessageDigest.getInstance(algorithm);
            } catch (NoSuchAlgorithmException var2) {
                throw new IllegalArgumentException(var2);
            }
        }

        private static byte[] getBytes(String string, Charset charset) {
            return string == null ? null : string.getBytes(charset);
        }

        public  boolean isBlank(CharSequence cs) {
            int strLen;
            if (cs != null && (strLen = cs.length()) != 0) {
                for(int i = 0; i < strLen; ++i) {
                    if (!Character.isWhitespace(cs.charAt(i))) {
                        return false;
                    }
                }

                return true;
            } else {
                return true;
            }
        }
    }
}
